package router

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"gitee.com/actor168/gitserver/pkg/auth"
	"gitee.com/actor168/gitserver/pkg/config"
	"gitee.com/actor168/gitserver/pkg/lazyregexp"
	"gitee.com/actor168/gitserver/pkg/pathutil"
	"gitee.com/actor168/gitserver/pkg/tool"
	"github.com/gin-gonic/gin"

	log "unknwon.dev/clog/v2"
)

type HTTPContext struct {
	*gin.Context
	OwnerName string
	OwnerSalt string
	RepoName  string
}

// askCredentials responses HTTP header and status which informs client to provide credentials.
func askCredentials(c *gin.Context, status int, text string) {
	c.Request.Header.Set("WWW-Authenticate", "Basic realm=\".\"")
	c.Status(status)
	c.Error(fmt.Errorf(text))
}

func HTTPContexter(c *gin.Context) {
	if strings.HasPrefix(c.Param("path"), "/raw") {
		c.Next()
		return
	}
	ownerName := c.Params.ByName("username")
	repoName := strings.TrimSuffix(c.Params.ByName(":reponame"), ".git")
	repoName = strings.TrimSuffix(repoName, ".wiki")

	// In case user requested a wrong URL and not intended to access Git objects.
	action := c.Params.ByName("path")
	if !strings.Contains(action, "git-") &&
		!strings.Contains(action, "info/") &&
		!strings.Contains(action, "HEAD") &&
		!strings.Contains(action, "objects/") {
		c.Status(500)
		c.Error(fmt.Errorf("unrecognized action %q", action))
		return
	}

	// Handle HTTP Basic Authentication
	if true {
		return
	}
	authHead := c.GetHeader("Authorization")
	if authHead == "" {
		askCredentials(c, http.StatusUnauthorized, "")
		return
	}

	auths := strings.Fields(authHead)
	if len(auths) != 2 || auths[0] != "Basic" {
		askCredentials(c, http.StatusUnauthorized, "")
		return
	}
	authUsername, authPassword, err := tool.BasicAuthDecode(auths[1])
	if err != nil {
		askCredentials(c, http.StatusUnauthorized, "")
		return
	}
	authUser, err := auth.Authenticator.Authenticate(authUsername, authPassword)
	if err == nil && authUser.FullName != "" {
		// authorize
		if flag, _ := auth.Authorizer.Authorize(authUser, ownerName); !flag {
			c.Status(http.StatusUnauthorized)
			log.Error("Failed to authenticate user [name: %s]: %v", authUsername, err)
			return
		}
	} else {
		c.Status(http.StatusUnauthorized)
		log.Error("Failed to authenticate user [name: %s]: %v", authUsername, err)
		return
	}
}

type serviceHandler struct {
	w         http.ResponseWriter
	r         *http.Request
	dir       string
	file      string
	ownerName string
	repoName  string
}

func (h *serviceHandler) setHeaderNoCache() {
	h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT")
	h.w.Header().Set("Pragma", "no-cache")
	h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
}

func (h *serviceHandler) setHeaderCacheForever() {
	now := time.Now().Unix()
	expires := now + 31536000
	h.w.Header().Set("Date", fmt.Sprintf("%d", now))
	h.w.Header().Set("Expires", fmt.Sprintf("%d", expires))
	h.w.Header().Set("Cache-Control", "public, max-age=31536000")
}

func (h *serviceHandler) sendFile(contentType string) {
	reqFile := path.Join(h.dir, h.file)
	fi, err := os.Stat(reqFile)
	if os.IsNotExist(err) {
		h.w.WriteHeader(http.StatusNotFound)
		return
	}

	h.w.Header().Set("Content-Type", contentType)
	h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size()))
	h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat))
	http.ServeFile(h.w, h.r, reqFile)
}

func serviceRPC(h serviceHandler, service string) {
	defer h.r.Body.Close()

	if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) {
		h.w.WriteHeader(http.StatusUnauthorized)
		return
	}
	h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service))

	var (
		reqBody = h.r.Body
		err     error
	)

	// Handle GZIP
	if h.r.Header.Get("Content-Encoding") == "gzip" {
		reqBody, err = gzip.NewReader(reqBody)
		if err != nil {
			log.Error("HTTP.Get: fail to create gzip reader: %v", err)
			h.w.WriteHeader(http.StatusInternalServerError)
			return
		}
	}

	var stderr bytes.Buffer
	cmd := exec.Command("git", service, "--stateless-rpc", h.dir)
	if service == "receive-pack" {
		cmd.Env = append(os.Environ(), ComposeHookEnvs(ComposeHookEnvsOptions{
			RepoName: h.repoName,
			RepoPath: h.dir,
		})...)
	}
	cmd.Dir = h.dir
	cmd.Stdout = h.w
	cmd.Stderr = &stderr
	cmd.Stdin = reqBody
	if err = cmd.Run(); err != nil {
		log.Error("HTTP.serviceRPC: fail to serve RPC '%s': %v - %s", service, err, stderr.String())
		h.w.WriteHeader(http.StatusInternalServerError)
		return
	}
}

type ComposeHookEnvsOptions struct {
	OwnerName string
	RepoName  string
	RepoPath  string
}

const (
	ENV_AUTH_USER_ID           = "GOGS_AUTH_USER_ID"
	ENV_AUTH_USER_NAME         = "GOGS_AUTH_USER_NAME"
	ENV_AUTH_USER_EMAIL        = "GOGS_AUTH_USER_EMAIL"
	ENV_REPO_OWNER_NAME        = "GOGS_REPO_OWNER_NAME"
	ENV_REPO_OWNER_SALT_MD5    = "GOGS_REPO_OWNER_SALT_MD5"
	ENV_REPO_ID                = "GOGS_REPO_ID"
	ENV_REPO_NAME              = "GOGS_REPO_NAME"
	ENV_REPO_CUSTOM_HOOKS_PATH = "GOGS_REPO_CUSTOM_HOOKS_PATH"
)

func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
	envs := []string{
		"SSH_ORIGINAL_COMMAND=1",
		ENV_REPO_OWNER_NAME + "=" + opts.OwnerName,
		ENV_REPO_NAME + "=" + opts.RepoName,
		ENV_REPO_CUSTOM_HOOKS_PATH + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
	}
	return envs
}

func serviceUploadPack(h serviceHandler) {
	serviceRPC(h, "upload-pack")
}

func serviceReceivePack(h serviceHandler) {
	serviceRPC(h, "receive-pack")
}

func getServiceType(r *http.Request) string {
	serviceType := r.FormValue("service")
	if !strings.HasPrefix(serviceType, "git-") {
		return ""
	}
	return strings.TrimPrefix(serviceType, "git-")
}

// FIXME: use process module
func gitCommand(dir string, args ...string) []byte {
	cmd := exec.Command("git", args...)
	cmd.Dir = dir
	out, err := cmd.Output()
	if err != nil {
		log.Error(fmt.Sprintf("Git: %v - %s", err, out))
	}
	return out
}

func updateServerInfo(dir string) []byte {
	return gitCommand(dir, "update-server-info")
}

func packetWrite(str string) []byte {
	s := strconv.FormatInt(int64(len(str)+4), 16)
	if len(s)%4 != 0 {
		s = strings.Repeat("0", 4-len(s)%4) + s
	}
	return []byte(s + str)
}

func getInfoRefs(h serviceHandler) {
	h.setHeaderNoCache()
	service := getServiceType(h.r)
	if service != "upload-pack" && service != "receive-pack" {
		updateServerInfo(h.dir)
		h.sendFile("text/plain; charset=utf-8")
		return
	}
	refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".")
	h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service))
	h.w.WriteHeader(http.StatusOK)
	_, _ = h.w.Write(packetWrite("# service=git-" + service + "\n"))
	_, _ = h.w.Write([]byte("0000"))
	_, _ = h.w.Write(refs)
}

func getTextFile(h serviceHandler) {
	h.setHeaderNoCache()
	h.sendFile("text/plain")
}

func getInfoPacks(h serviceHandler) {
	h.setHeaderCacheForever()
	h.sendFile("text/plain; charset=utf-8")
}

func getLooseObject(h serviceHandler) {
	h.setHeaderCacheForever()
	h.sendFile("application/x-git-loose-object")
}

func getPackFile(h serviceHandler) {
	h.setHeaderCacheForever()
	h.sendFile("application/x-git-packed-objects")
}

func getIdxFile(h serviceHandler) {
	h.setHeaderCacheForever()
	h.sendFile("application/x-git-packed-objects-toc")
}

var routes = []struct {
	re      *lazyregexp.Regexp
	method  string
	handler func(serviceHandler)
}{
	{lazyregexp.New("(.*?)/git-upload-pack$"), "POST", serviceUploadPack},
	{lazyregexp.New("(.*?)/git-receive-pack$"), "POST", serviceReceivePack},
	{lazyregexp.New("(.*?)/info/refs$"), "GET", getInfoRefs},
	{lazyregexp.New("(.*?)/HEAD$"), "GET", getTextFile},
	{lazyregexp.New("(.*?)/objects/info/alternates$"), "GET", getTextFile},
	{lazyregexp.New("(.*?)/objects/info/http-alternates$"), "GET", getTextFile},
	{lazyregexp.New("(.*?)/objects/info/packs$"), "GET", getInfoPacks},
	{lazyregexp.New("(.*?)/objects/info/[^/]*$"), "GET", getTextFile},
	{lazyregexp.New("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject},
	{lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile},
	{lazyregexp.New("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile},
}

func getGitRepoPath(dir string) (string, error) {
	if !strings.HasSuffix(dir, ".git") {
		dir += ".git"
	}

	filename := filepath.Join(config.Conf.Dir, dir)
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return "", err
	}

	return filename, nil
}

func HTTP(c *gin.Context) {
	if strings.HasPrefix(c.Param("path"), "/raw") {
		c.Next()
		return
	}
	for _, route := range routes {
		reqPath := c.Request.URL.Path
		m := route.re.FindStringSubmatch(reqPath)
		if m == nil {
			continue
		}

		// We perform check here because route matched in cmd/web.go is wider than needed,
		// but we only want to output this message only if user is really trying to access
		// Git HTTP endpoints.

		if route.method != c.Request.Method {
			c.Status(http.StatusNotFound)
			c.Abort()
			return
		}

		cleaned := pathutil.Clean(m[1])
		if m[1] != "/"+cleaned {
			c.JSON(http.StatusBadRequest, "Request path contains suspicious characters")
			c.Abort()
			return
		}

		file := strings.TrimPrefix(reqPath, cleaned)
		dir, err := getGitRepoPath(cleaned)
		if err != nil {
			log.Warn("HTTP.getGitRepoPath: %v", err)
			c.Status(http.StatusNotFound)
			c.Abort()
			return
		}

		route.handler(serviceHandler{
			w:    c.Writer,
			r:    c.Request,
			dir:  dir,
			file: file,

			ownerName: c.GetString("username"),
			repoName:  c.GetString("reponame"),
		})
		c.Abort()
		return
	}

	c.Status(http.StatusNotFound)
	c.Abort()
}
